package com.yanggu.sa_token.basic_demo.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.dao.SaTokenDaoRedisJackson;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaAnnotationStrategy;
import com.yanggu.sa_token.basic_demo.StpUserUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Autowired
    private SaTokenDaoRedisJackson saTokenDao;

    @PostConstruct
    public void init() {
        // 重写Sa-Token的注解处理器，增加注解合并功能
        SaAnnotationStrategy.instance.getAnnotation = AnnotatedElementUtils::getMergedAnnotation;
        SaManager.setSaTokenDao(saTokenDao);
    }

    // 注册 Sa-Token 拦截器，打开注解式鉴权功能 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能 
        registry.addInterceptor(new SaInterceptor(handle -> {
            //info4需要admin登录才能访问
            SaRouter.match("/StpUserUtil/info4").check(StpUtil::checkLogin);

            //info5需要user登录才能访问
            SaRouter.match("/StpUserUtil/info5").check(StpUserUtil::checkLogin);

            //info6需要admin和user都登录才能访问
            SaRouter.match("/StpUserUtil/info6").check(() -> {
                StpUserUtil.checkLogin();
                StpUtil.checkLogin();
            });

            //info7需要admin或者user任意一个登录才能访问
            SaRouter.match("/StpUserUtil/info7").check(() -> {
                if (!(StpUtil.isLogin() || StpUserUtil.isLogin())) {
                    throw new SaTokenException("请登录后再访问接口");
                }
            });
        })).addPathPatterns("/**");
    }

}
